package com.zelma.house.controller;

import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zelma.house.dao.ResourceDao;
import com.zelma.house.entity.ResourceEntity;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 此类是真正的定时任务处理类
 *
 * （定时任务功能逻辑）在此类完成
 *
 * （定时对账  定时发短信  定时任务）
 *
 */


@Component
public class A {
    private static Logger logger = LoggerFactory.getLogger(A.class);

    @Autowired
    ResourceDao resourceDao;

    @Autowired
    RestHighLevelClient client;
    //xxl-job--wq
    @XxlJob("demoJobHandler")
    public ReturnT<String> execute() throws IOException {
        System.out.println("项目初始化把商品信息初始化到ES索引当中");
        List<ResourceEntity> list = resourceDao.selectList(null);
        BulkRequest bulkRequest = new BulkRequest();
        for (ResourceEntity resourceEntity : list) {
            IndexRequest request = new IndexRequest("resource");
            request.id(resourceEntity.getResourceId().toString());
            String jsonString = JSONObject.toJSONString(resourceEntity);
            request.source(jsonString, XContentType.JSON);
            bulkRequest.add(request);
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return ReturnT.SUCCESS;
    }

    /**
     * 2、分片广播任务--wq
     */
    @XxlJob("shardingJobHandler")
    public void shardingJobHandler() throws Exception {
        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();
        XxlJobHelper.log("分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);
        List<ResourceEntity> list=resourceDao.selecthouse(shardIndex,shardTotal);
        list.forEach(c->{
            System.out.println("id"+c.getResourceId()+"title:"+c.getResourceName());
        });
    }

}
